<template>
  <div>
    <div style="border: 1px solid #ccc;">
      <Toolbar
          style="border-bottom: 1px solid #ccc"
          :editor="editor"
          :defaultConfig="toolbarConfig"
      />
      <Editor
          style="height: 400px"
          v-model="html"
          :defaultConfig="editorConfig"
          @onChange="onChange"
          @onCreated="onCreated"
      />
      <mention-modal
          v-if="isShowModal"
          @hideMentionModal="hideMentionModal"
          @insertMention="insertMention"
      ></mention-modal>
      <!-- 三维模型选择模态框 -->
      <model-select-modal
          :visible.sync="isShowModelSelectModal"
          :model-options="modelOptions"
          @select="handleModelSelect"
      ></model-select-modal>
    </div>
    <div style="margin-top: 10px;">
      <textarea v-model="html" style="width: 100%; height: 500px;"></textarea>
    </div>
  </div>
</template>

<script>
import { Boot } from '@wangeditor/editor'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import mentionModule from '@wangeditor/plugin-mention'
import MentionModal from "./MentionModal.vue";
// 引入模型选择模态框组件
import ModelSelectModal from "./ModelSelectModal.vue";
class MyButtonMenu {
  constructor() {
    this.title = '三维模型',
        this.tag = 'button'
  }
  getValue() { return '' }
  isActive() { return false }
  isDisabled() { return false }
  exec(editor) {  // 移除多余的 value 参数
    if (this.isDisabled(editor)) return
    // 触发自定义事件，传递editor实例
    document.dispatchEvent(new CustomEvent('show-model-select', {
      detail: { editor }
    }));
  }
}
const menuConf = {
  key: 'my-menu-1', // menu key ，唯一。注册之后，需通过 toolbarKeys 配置到工具栏
  factory() {
    return new MyButtonMenu()
  },
}
Boot.registerMenu(menuConf)
// 注册插件
Boot.registerModule(mentionModule)

export default {
  name: 'MyEditorWithMention',
  components: { Editor, Toolbar, MentionModal, ModelSelectModal },
  data() {
    return {
      editor: null,
      html: '<p>你好<span data-w-e-type="mention" data-w-e-is-void data-w-e-is-inline data-value="A张三" data-info="%7B%22id%22%3A%22a%22%7D">@A张三</span></p>',
      toolbarConfig: {
        insertKeys: {
          index: 0,
          keys: 'my-menu-1'
        }
      },
      editorConfig: {
        placeholder: '请输入内容...',

        EXTEND_CONF: {
          mentionConfig: {
            showModal: this.showMentionModal,
            hideModal: this.hideMentionModal,
          },
        },
      },
      isShowModal: false,
      // 新增模型选择相关数据
      isShowModelSelectModal: false,
      currentEditor: null,
      modelOptions: [
        { id: 1, name: '建筑模型' },
        { id: 2, name: '机械模型' },
        { id: 3, name: '人物模型' }
      ]
    }
  },
  // 添加事件监听
  mounted() {
    this.handleShowModelSelect = (e) => {
      this.showModelSelectModal(e.detail.editor);
    };
    document.addEventListener('show-model-select', this.handleShowModelSelect);
  },

  methods: {
    onCreated(editor) {
      this.editor = Object.seal(editor) // 【注意】一定要用 Object.seal() 否则会报错
      // 初始化时将光标定位到内容末尾
      editor.focus(true); // focus(true) 会将光标移动到内容末尾
    },
    onChange(editor) {
      this.curHtml = editor.getHtml()
    },
    showMentionModal() {
      this.isShowModal = true
    },
    hideMentionModal() {
      this.isShowModal = false
    },
    insertMention(id, name) {
      const mentionNode = {
        type: 'mention', // 必须是 'mention'
        value: name,
        info: { id },
        children: [{ text: '' }], // 必须有一个空 text 作为 children
      }
      const editor = this.editor
      if (editor) {
        editor.restoreSelection() // 恢复选区
        editor.deleteBackward('character') // 删除 '@'
        editor.insertNode(mentionNode) // 插入 mention
        editor.move(1) // 移动光标
      }
    },
    // 新增模型选择相关方法
    showModelSelectModal(editor) {
      // 确保编辑器实例有效
      if (editor && typeof editor.insertText === 'function') {
        this.currentEditor = editor;
        this.isShowModelSelectModal = true;
      } else {
        console.error('无效的编辑器实例');
        // 尝试使用主编辑器实例
        if (this.editor) {
          this.currentEditor = this.editor;
          this.isShowModelSelectModal = true;
        }
      }
    },
    hideModelSelectModal() {
      this.isShowModelSelectModal = false;
    },
    handleModelSelect(model) {
      try {
        // 双重检查编辑器实例
        if (this.currentEditor && typeof this.currentEditor.insertText === 'function') {
          // 恢复编辑器选区（关键修复）
          this.currentEditor.restoreSelection();
          // 插入文本
          const text = `[三维模型: ${model.name}]`;
          this.currentEditor.insertText(text);
          // 确保光标在插入文本之后（优化移动逻辑）
          this.currentEditor.move(1);
          // 确保编辑器获得焦点（新增）
          // this.currentEditor.focus();
          this.isShowModelSelectModal = false; // 手动关闭模态框
        } else {
          this.isShowModelSelectModal = false;
        }
      } catch (error) {
        this.isShowModelSelectModal = false; // 出错时确保模态框关闭
      } finally {
        this.currentEditor = null; // 无论成功失败都重置
      }
    }
  },
  beforeDestroy() {
    const editor = this.editor;
    if (editor == null) return;
    editor.destroy();
    // 移除事件监听
    document.removeEventListener('show-model-select', this.handleShowModelSelect);
  },
}
</script>

<style src="@wangeditor/editor/dist/css/style.css"></style>
